package kr.hkit.Powerjava.chapter26.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import kr.hkit.Powerjava.chapter26.DbProperties;


public class ConnectionFactory {
	private String driver; //com.mysql.jdbc.DRIVER
	private String url;
	private String user;
	private String password;
	
	private static ConnectionFactory instance = new ConnectionFactory();

	public static Connection getConnection() {
		return instance.createConnection();
	}
	
	private ConnectionFactory() {
		loadProperties();
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			System.err.printf("%s\n","MySQL Driver Not Found");
			System.exit(-1);
		}
	}
	
	private Connection createConnection() {
		Connection con = null;
		try {
			con = DriverManager.getConnection(url, user, password);
			System.out.printf("%s\n","MySQL Connection Success.");
		} catch (SQLException e) {
			System.err.println("ERROR : Unable Connect to MySQL.");
		}		
		return con;
	}
	
	private void loadProperties() {
		Properties prop = DbProperties.loadProperties("dbcon.xml");
		driver=prop.getProperty("DRIVER");
		url= prop.getProperty("URL");
		user= prop.getProperty("USER");
		password= prop.getProperty("PASSWORD");
		
	}
	
}
